<template>
  <div class="rank-view">
    <div class="rank-container">
      <div class="rank-header">
        <router-link to="/draw-a-fish">draw</router-link>
        <router-link to="/draw-a-fish/tank">tank</router-link>
        <router-link to="/draw-a-fish/rank">rankings</router-link>
        <a href="#" @click.prevent="showProfile">profile</a>
        <a href="#" @click.prevent="showLogin">Login</a>
      </div>

      <h1>Fish Ranking</h1>

      <div class="sort-buttons">
        <button
          :class="{ active: sortBy === 'hot' }"
          @click="setSortBy('hot')"
        >
          Sort by Hot ↓
        </button>
        <button
          :class="{ active: sortBy === 'score' }"
          @click="setSortBy('score')"
        >
          Sort by Score
        </button>
        <button
          :class="{ active: sortBy === 'date' }"
          @click="setSortBy('date')"
        >
          Sort by Date
        </button>
        <button
          :class="{ active: sortBy === 'random' }"
          @click="setSortBy('random')"
        >
          Random Order
        </button>
      </div>

      <div class="fish-grid">
        <div v-for="(fish, index) in sortedFishes" :key="index" class="fish-card">
          <div class="fish-image">
            <canvas
              :ref="`fishCanvas${index}`"
              class="fish-canvas"
              width="200"
              height="150"
            />
          </div>
          <div class="fish-info">
            <p class="fish-name">Fish #{{ index + 1 }}</p>
            <p class="fish-score">Score: {{ fish.score }}</p>
            <p class="fish-date">{{ formatDate(fish.date) }}</p>
            <div class="fish-actions">
              <button @click="voteFish(index)" class="btn-vote">
                👍 {{ fish.votes }}
              </button>
              <button @click="viewFish(index)" class="btn-view">View</button>
            </div>
          </div>
        </div>
      </div>

      <div v-if="fishes.length === 0" class="empty-state">
        <p>No fish to rank yet. Go draw one!</p>
        <router-link to="/draw-a-fish" class="btn-draw">Draw a Fish</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

const sortBy = ref('hot')
const fishes = ref([])
const sortReverse = ref(false)

onMounted(() => {
  generateSampleFishes()
})

const generateSampleFishes = () => {
  const colors = ['#ff0000', '#00cc00', '#0000ff', '#ffff00', '#ff8800', '#000000']
  fishes.value = Array.from({ length: 12 }, (_, i) => ({
    id: i,
    score: Math.floor(Math.random() * 100),
    votes: Math.floor(Math.random() * 50),
    date: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000),
    color: colors[Math.floor(Math.random() * colors.length)]
  }))

  // 绘制示例鱼
  fishes.value.forEach((fish, index) => {
    setTimeout(() => {
      drawSampleFish(index, fish.color)
    }, 100)
  })
}

const drawSampleFish = (index, color) => {
  const canvasRef = document.querySelector(`canvas[data-index="${index}"]`)
  if (!canvasRef) {
    // 尝试通过其他方式获取canvas
    const allCanvases = document.querySelectorAll('.fish-canvas')
    if (allCanvases[index]) {
      const ctx = allCanvases[index].getContext('2d')
      drawFishShape(ctx, color, allCanvases[index].width, allCanvases[index].height)
    }
  } else {
    const ctx = canvasRef.getContext('2d')
    drawFishShape(ctx, color, canvasRef.width, canvasRef.height)
  }
}

const drawFishShape = (ctx, color, width, height) => {
  // 背景
  ctx.fillStyle = '#e8f4f8'
  ctx.fillRect(0, 0, width, height)

  // 鱼身
  ctx.fillStyle = color
  ctx.beginPath()
  ctx.ellipse(width / 2, height / 2, 40, 25, 0, 0, Math.PI * 2)
  ctx.fill()

  // 鱼尾
  ctx.beginPath()
  ctx.moveTo(width / 2 + 40, height / 2)
  ctx.lineTo(width / 2 + 60, height / 2 - 20)
  ctx.lineTo(width / 2 + 60, height / 2 + 20)
  ctx.closePath()
  ctx.fill()

  // 鱼眼
  ctx.fillStyle = 'white'
  ctx.beginPath()
  ctx.arc(width / 2 - 15, height / 2, 5, 0, Math.PI * 2)
  ctx.fill()

  ctx.fillStyle = 'black'
  ctx.beginPath()
  ctx.arc(width / 2 - 15, height / 2, 3, 0, Math.PI * 2)
  ctx.fill()
}

const sortedFishes = computed(() => {
  let sorted = [...fishes.value]

  if (sortBy.value === 'hot') {
    sorted.sort((a, b) => b.date - a.date)
  } else if (sortBy.value === 'score') {
    sorted.sort((a, b) => b.score - a.score)
  } else if (sortBy.value === 'date') {
    sorted.sort((a, b) => b.date - a.date)
  } else if (sortBy.value === 'random') {
    sorted = sorted.sort(() => Math.random() - 0.5)
  }

  return sortReverse.value ? sorted.reverse() : sorted
})

const setSortBy = (type) => {
  if (sortBy.value === type) {
    sortReverse.value = !sortReverse.value
  } else {
    sortBy.value = type
    sortReverse.value = false
  }
}

const voteFish = (index) => {
  fishes.value[index].votes++
  fishes.value[index].score += 5
}

const viewFish = (index) => {
  alert(`Viewing fish #${index + 1}`)
}

const showProfile = () => {
  alert('Profile page')
}

const showLogin = () => {
  alert('Login page')
}

const formatDate = (date) => {
  const now = new Date()
  const diff = now - date
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (hours < 1) return 'just now'
  if (hours < 24) return `${hours}h ago`
  if (days < 7) return `${days}d ago`
  return date.toLocaleDateString()
}
</script>

<style scoped>
.rank-view {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.rank-container {
  background: white;
  border-radius: 10px;
  padding: 30px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
  width: 100%;
  max-width: 1200px;
}

.rank-header {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.rank-header a,
.rank-header router-link {
  color: #667eea;
  text-decoration: none;
  font-weight: bold;
}

.rank-header a:hover,
.rank-header router-link:hover {
  text-decoration: underline;
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
}

.sort-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 30px;
  flex-wrap: wrap;
  justify-content: center;
}

.sort-buttons button {
  padding: 10px 20px;
  background: #f0f0f0;
  border: 2px solid transparent;
  border-radius: 5px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.2s;
}

.sort-buttons button:hover {
  background: #e0e0e0;
}

.sort-buttons button.active {
  background: #667eea;
  color: white;
  border-color: #667eea;
}

.fish-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.fish-card {
  background: #f9f9f9;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.fish-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.fish-image {
  width: 100%;
  height: 150px;
  background: #e8f4f8;
  display: flex;
  align-items: center;
  justify-content: center;
}

.fish-canvas {
  width: 100%;
  height: 100%;
}

.fish-info {
  padding: 15px;
}

.fish-name {
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.fish-score {
  color: #666;
  font-size: 14px;
  margin-bottom: 5px;
}

.fish-date {
  color: #999;
  font-size: 12px;
  margin-bottom: 10px;
}

.fish-actions {
  display: flex;
  gap: 10px;
}

.btn-vote,
.btn-view {
  flex: 1;
  padding: 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.2s;
}

.btn-vote {
  background: #48bb78;
  color: white;
}

.btn-vote:hover {
  background: #38a169;
}

.btn-view {
  background: #667eea;
  color: white;
}

.btn-view:hover {
  background: #5568d3;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.btn-draw {
  display: inline-block;
  margin-top: 15px;
  padding: 12px 25px;
  background: #667eea;
  color: white;
  text-decoration: none;
  border-radius: 5px;
  font-weight: bold;
}

.btn-draw:hover {
  background: #5568d3;
}
</style>

